# coding=utf-8

from collections import namedtuple
import os
import re
FILE = r'C:\chenchang\temp\vimdoc\LangImpl\LangImpl01.html'

arr =[
    '1. Tutorial Introduction and the Lexer',
    '2. Implementing a Parser and AST',
    '3. Code generation to LLVM IR',
    '4. Adding JIT and Optimizer Support',
    '5. Extending the Language: Control Flow',
    '6. Extending the Language: User-defined Operators',
    '7. Extending the Language: Mutable Variables',
    '8. Compiling to Object Code',
    '9. Adding Debug Information',
    '10. Conclusion and other useful LLVM tidbits',
]

t = namedtuple('FileItem', 'text href id sf')
st = namedtuple('SubFileItem', 'text anchor id')

def FileList():
    return [t(arr[i], "LangImpl" + ("0" + str(i+1))[-2:] + ".html", str(i+1), None) for i in range(10)]

PATTERN = r'<li><a class="reference internal" href="(.*)" id="(.*)">(.*)</a><(/li|ul)>'

def SubFileList(FILE):
    rs = []
    with open(FILE) as f:
        for r in f.readlines():
            m = re.search(PATTERN, r.strip())
            if m:
                rs.append(st(anchor=m.group(1), id=m.group(2), text=m.group(3)))
    return rs

def Data():
    return [t(x.text, x.href, x.id, SubFileList(os.path.join(r'C:\chenchang\temp\vimdoc\LangImpl', x.href))) for x in FileList()]

NAVI_TMPL = """		<navPoint id="{ID}" playOrder="{PLAY_ORDER}">
			<navLabel>
				<text>
					{TEXT}
				</text>
			</navLabel>
			<content src="{HREF}" />{SUBNAV}
		</navPoint>"""

SUBNAV_TMPL = '\n' + '\n'.join(['\t' + x for x in NAVI_TMPL.split('\n')]).replace('{SUBNAV}', '')

NCX_TMPL = """<?xml version="1.0"?>
<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN"
 "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
 <head>
 </head>
        <docTitle>
               <text>Book title</text>
        </docTitle>
	<navMap>
{CONTEXT}
	</navMap>
</ncx>
"""

po = 0
def BuildNCX():
    global po
    po = 0
    def PlayOrder():
        global po
        po += 1
        return po
    return NCX_TMPL.format(CONTEXT='\n'.join([NAVI_TMPL.format(ID="ch" + f.id, PLAY_ORDER=PlayOrder(), TEXT=f.text, HREF=f.href, SUBNAV = \
            '' + ''.join([SUBNAV_TMPL.format(ID="ch" + f.id + "_" + sf.id, PLAY_ORDER=PlayOrder(), TEXT=("%s.%s " % (f.id, ix+1)) + sf.text, HREF=f.href + sf.anchor) for ix, sf in enumerate(f.sf)]) \
            ) for f in Data()]))

def BuildTOC():
    # jjj
    TOC_TMPL = """<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TOC</title>
<!-- <link type="text/css" href="kf8.css" media="amzn-kf8" rel="Stylesheet"/> -->
<!-- <link type="text/css" href="mobi.css" media="amzn-mobi" rel="Stylesheet"/> -->
<!-- <link type="text/css" href="styles.css" rel="Stylesheet"/> -->
</head>
<body>

<h1 id="toc">Table of Contents</h1>

<ul>
{ITEMS}</ul>
</body>
</html>
"""
    LVL1_TMPL = """    <li><a href="{HREF}">{TEXT}</a>
    <ul>
{ITEMS}    </ul>
    </li>
"""
    LVL2_TMPL = """        <li><a href="{HREF}">{TEXT}</a></li>
"""
    return TOC_TMPL.format(ITEMS=''.join([LVL1_TMPL.format(HREF=f.href, TEXT=f.text, ITEMS= \
            ''.join([LVL2_TMPL.format(HREF=f.href + sf.anchor, TEXT=sf.text) for sf in f.sf]) \
            ) for f in Data()]))
# <li><a href="text.html#id2">Text Styling</a></li>
# <li><a href="text.html#id3">Text Alignment</a></li>
# <li><a href="text.html#id4">Text Shadow</a></li>
# <li><a href="text.html#id5">Drop Caps</a></li>
# <li><a href="text.html#id6">Display Dimension</a></li>
# <li><a href="text.html#id7">Border</a></li>
# <li><a href="text.html#id8">Background</a></li>
# <li><a href="text.html#id9">Border Styling</a></li>
# <li><a href="text.html#id10">Tables</a></li>

    # 1g
    pass

if __name__ == "__main__":
    print(BuildTOC())
    with open(os.path.join(r'C:\chenchang\temp\vimdoc\LangImpl', "toc.html"), "w") as f:
        f.write(BuildTOC())

    # print(NAVI_TMPL)
    # print(SUBNAV_TMPL)
    # print(BuildNCX())
    # print(BuildNCX())
    # with open(os.path.join(r'C:\chenchang\temp\vimdoc\LangImpl', "LangImpl.ncx"), "w") as f:
    #     f.write(BuildNCX())

    # for f in Data():
    #     print(f.text, f.href, f.id)
    #     for sf in f.sf:
    #         print(' '* 4,sf.text, sf.anchor, sf.id)
